package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    //百度地图服务端ak
    @Value("${sky.baiduMap.ak}")
    private String ak;

    //店铺地址
    @Value("${sky.baiduMap.address}")
    private String shopAddress;

    //百度地图地址编码Api http地址
    private static final String url = "https://api.map.baidu.com/geocoding/v3";

    //百度地图导航Api http地址
    private static final String directionUrl = "https://api.map.baidu.com/directionlite/v1/driving";
    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理各种业务异常(地址簿为空,购物车为空)
        Long addressId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressId);
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查用户是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName()+addressBook.getDetail());

        //查询购物车中的数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if(shoppingCarts == null || shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //往订单中插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPayStatus(Orders.UN_PAID);
        orderMapper.insert(orders);

        //往订单明细表中插入多条数据
        List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
        for(ShoppingCart cart : shoppingCarts){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertBatch(orderDetails);

        //清空当前用户的购物车
        shoppingCartMapper.deleteByUserId(userId);

        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    /**
     * 历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);

        //先查出orders
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        Long total = page.getTotal();
        List<Orders> records = page.getResult();

        //再查每个order对应的orderDetails
        List<OrderVO> orderVOs = new ArrayList<OrderVO>();
        for(Orders record : records){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(record, orderVO);

            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(record.getId());
            orderVO.setOrderDetailList(orderDetails);
            orderVOs.add(orderVO);
        }

        return new PageResult(total, orderVOs);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    public void cancelOrder(Long id) throws Exception {
        Long userId = BaseContext.getCurrentId();

        Orders ordersDB = orderMapper.getById(id);

        //检验订单是否存在
        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if(ordersDB.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .userId(userId)
                .status(Orders.CANCELLED)
                .build();

        if(ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01)
            );
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");

        orderMapper.update(orders);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        Long userId= BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartMapper.inserBatch(shoppingCarts);
    }

    /**
     * 管理员根据条件动态查询
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult adminPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        Long total = page.getTotal();
        List<Orders> ordersList = page.getResult();
        List<OrderVO> orderVOList = new ArrayList<>();
        for(Orders order:ordersList){
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
            List<String> orderDishList = orderDetailList.stream().map(x->{
                String orderDish = x.getName()+"*"+x.getNumber()+";";
                return orderDish;
            }).collect(Collectors.toList());
            String orderDishes =  String.join("", orderDishList);
            orderVO.setOrderDishes(orderDishes);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }

        return new PageResult(total, orderVOList);
    }

    /**
     * 管理员取消订单
     * @param ordersCancelDTO
     */
    public void adminCancelOrderd(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        Integer payStatus = orders.getPayStatus();
        if(payStatus == 1){
            //用户已支付,需要退款
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01)
            );
        }

        Orders ordes1 = new Orders();
        ordes1.setId(ordersCancelDTO.getId());
        ordes1.setStatus(Orders.CANCELLED);
        ordes1.setCancelReason(ordersCancelDTO.getCancelReason());
        ordes1.setCancelTime(LocalDateTime.now());
        orderMapper.update(ordes1);
    }

    /**
     * 统计各种状态的订单
     * @return
     */
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmedOrder = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmedOrder = orderMapper.countByStatus(Orders.CONFIRMED);
        Integer deliveryInProgressOrder = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmedOrder);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgressOrder);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmedOrder);

        return orderStatisticsVO;
    }

    /**
     * 管理员拒绝订单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        Orders orderDB = orderMapper.getById(id);

        //校验订单是否存在
        if(orderDB.getStatus() == null || !orderDB.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //更新订单状态
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders orderDB = orderMapper.getById(id);
        //检查订单状态是否为配送中
        if(orderDB.getStatus() == null || !orderDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        //更新订单表
        orderMapper.update(orders);
    }

    /**
     * 检查收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address){
        Map<String,String> map = new HashMap<>();
        map.put("address",shopAddress);
        map.put("ak",ak);
        map.put("output","json");

        String shopCordinate = HttpClientUtil.doGet(url,map);
        JSONObject jsonObject = JSON.parseObject(shopCordinate);

        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //获取店铺的经纬度
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");

        // 使用BigDecimal保留6位小数
        BigDecimal shopLng = new BigDecimal(location.getString("lng")).setScale(6, RoundingMode.HALF_UP);
        BigDecimal shopLat = new BigDecimal(location.getString("lat")).setScale(6, RoundingMode.HALF_UP);

        String shopLatLng = shopLat + "," + shopLng;

        //获取收货地址的经纬度
        map.put("address",address);
        String userCordinate = HttpClientUtil.doGet(url,map);
        JSONObject userJsonObject = JSON.parseObject(userCordinate);

        if(!userJsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("用户收货地址解析失败");
        }
        JSONObject userResult = userJsonObject.getJSONObject("result");
        JSONObject userLocation = userResult.getJSONObject("location");

        // 使用BigDecimal保留6位小数
        BigDecimal userLng = new BigDecimal(userLocation.getString("lng")).setScale(6, RoundingMode.HALF_UP);
        BigDecimal userLat = new BigDecimal(userLocation.getString("lat")).setScale(6, RoundingMode.HALF_UP);

        String userLatLng = userLat + "," + userLng;

        //路线规划
        Map<String,String> directionParam = new HashMap<>();
        directionParam.put("origin",shopLatLng);
        directionParam.put("destination",userLatLng);
        directionParam.put("ak",ak);
        directionParam.put("steps_info","0");

        String json = HttpClientUtil.doGet(directionUrl,directionParam);

        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }
        jsonObject = JSON.parseObject(json);

        //数据解析
        JSONObject directionResult = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) directionResult.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        */

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Integer OrderPaidStatus = Orders.PAID;
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;

        LocalDateTime checkOutTime = LocalDateTime.now();

        String orderNumber = ordersPaymentDTO.getOrderNumber();

        log.info("调用updateStatus,用于替换微信支付更新数据库状态的问题");
        orderMapper.updateStatus(OrderStatus,OrderPaidStatus,checkOutTime,orderNumber);

        Orders ordersDB = orderMapper.getByNumber(orderNumber);

        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type",1); //1表示来单提醒,2表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:" + orderNumber);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    /**
     * 确认订单
     * @param id
     */
    public void confirm(Long id) {
        Orders ordersDB = orderMapper.getById(id);

        if(ordersDB.getStatus() == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);

        orderMapper.update(orders);
    }

    public void reminder(Long id) {
        Orders ordersDB = orderMapper.getById(id);

        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号: " + ordersDB.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
